package com.dwb.common.upload;

import com.dwb.config.BizException;
import com.dwb.result.Result;
import io.swagger.annotations.Api;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author manke
 * @Date 2020/6/23 17:13
 * @Version 0.0.1
 */
@RestController
@Api(value = "file", description = "文件上传控制器")
@RequestMapping("/upload")
public class Upload {

    @PostMapping("/uploadFile")
    public Result<String> uploadFileTest(@RequestParam("file") MultipartFile File) {
        return uploadFile(File);
    }

    public Result<String> uploadFile(MultipartFile zipFile) {
        Result<String> result = Result.newSuccess();
        String targetFilePath = "D:\\test\\uploadTest";
        String fileName = UUID.randomUUID().toString().replace("-", "");
        File targetFile = new File(targetFilePath + File.separator + fileName);

        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(targetFile);
            IOUtils.copy(zipFile.getInputStream(), fileOutputStream);
        } catch (IOException e) {
            return Result.newError("上传失败");
        } finally {
            try {
                assert fileOutputStream != null;
                fileOutputStream.close();
            } catch (IOException e) {
                throw new BizException(-1,"未知错误");

            }
        }
        result.setDataMap(targetFilePath+"\\"+fileName);
        return result;
    }
}


